#pragma once

#include "messageshowarea.h"
#include<QScrollBar>
#include<QGridLayout>
#include<QPushButton>
#include<QLabel>
#include<QPen>
#include<QPainter>
#include<QPainterPath>
#include<QTimer>
#include"debug.h"

#include"model/data.h"
#include"userinfowidget.h"
#include"mainWidget.h"
using namespace model;
MessageShowArea::MessageShowArea()
{
    // 1. 初始化基本属性
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    this->setWidgetResizable(true);
    // 设置滚动条的样式
    this->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 2px; background-color: rgb(240, 240, 240); }");
    this->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height: 0;}");
    this->setStyleSheet("QScrollArea { border: none; }");

    // 2. 创建 Container 这样的 widget, 作为包含内部元素的容器
    container = new QWidget();
    this->setWidget(container);

    // 3. 给 container 添加布局管理器
    QVBoxLayout* layout = new QVBoxLayout();
    layout->setSpacing(0);
    layout->setContentsMargins(0, 0, 0, 0);
    container->setLayout(layout);

//添加 "构造测试数据" 逻辑.
// #if TEST_UI
//     UserInfo userInfo;
//     userInfo.userId = QString::number(1000);
//     userInfo.name = "张三";
//     userInfo.description = "从今天开始认真敲代码";
//     userInfo.avatar = QIcon(":/resource/Image/defaultAvatar.png");
//     userInfo.phone = "18612345678";
//     Message message = Message::makeMessage(TEXT_TYPE, "", userInfo, QString("这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息").toUtf8(),"");
//     this->addMessage(false, message);

//     for (int i = 1; i <= 30; ++i) {
//         UserInfo userInfo;
//         userInfo.userId = QString::number(1000 + i);
//         userInfo.name = "张三" + QString::number(i);
//         userInfo.description = "从今天开始认真敲代码";
//         userInfo.avatar = QIcon(":/resource/Image/defaultAvatar.png");
//         userInfo.phone = "18612345678";
//         Message message = Message::makeMessage(TEXT_TYPE, "", userInfo, (QString("这是一条测试消息") + QString::number(i)).toUtf8(), "");
//         this->addMessage(true, message);
//     }
// #endif
 }

void MessageShowArea::addMessage(bool isLeft, const Message &message)
{
    // 构造 MessageItem, 添加到布局管理器中.
    MessageItem* messageItem = MessageItem::makeMessageItem(isLeft, message);
    container->layout()->addWidget(messageItem);
}
void MessageShowArea::addFrontMessage(bool isLeft, const Message &message)
{
    MessageItem* messageItem = MessageItem::makeMessageItem(isLeft, message);
    QVBoxLayout* layout = dynamic_cast<QVBoxLayout*>(container->layout());
    layout->insertWidget(0, messageItem);
}
void MessageShowArea::clear()
{
    // 遍历布局管理器, 删除里面的元素
    QLayout* layout = container->layout();
    for (int i = layout->count() - 1; i >= 0; --i) {
        QLayoutItem* item = layout->takeAt(i);
        if (item != nullptr && item->widget() != nullptr) {
            delete item->widget();
        }
    }
}
void MessageShowArea::scrollToEnd()
{
    // 实现思路:
    // 拿到滚动区域中的滚动条(垂直滚动条)
    // 获取到滚动条的最大值
    // 根据最大值, 设置滚动条的滚动位置.
    // 为了使滚动效果更佳, 能够在界面绘制好之后进行滚动条的设置
    // 给这里的滚动操作, 加上个 "延时"

    QTimer* timer = new QTimer();
    connect(timer, &QTimer::timeout, this, [=]() {
        // 获取到垂直滚动条的最大值
        int maxValue = this->verticalScrollBar()->maximum();
        // 设置滚动条的滚动位置
        this->verticalScrollBar()->setValue(maxValue);

        timer->stop();
        timer->deleteLater();
    });
    timer->start(500);
}

MessageItem::MessageItem(bool isleft)
    :isleft(isleft)
{

}
//////////////////////////////////
//创建具体的消息项目
//////////////////////////////////
MessageItem *MessageItem::makeMessageItem(bool isLeft, const Message &message)
{
    // 1. 创建对象和布局管理器
    MessageItem* messageItem = new MessageItem(isLeft);
    QGridLayout* layout = new QGridLayout();
    layout->setContentsMargins(30, 10, 40, 0);
    layout->setSpacing(10);
    // 这个 MessageItem 最低不能低于 100
    messageItem->setMinimumHeight(100);
    messageItem->setLayout(layout);

    // 2. 创建头像
    QPushButton* avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(40, 40);
    avatarBtn->setIconSize(QSize(40, 40));
    avatarBtn->setIcon(message.sender.avatar);
    avatarBtn->setStyleSheet("QPushButton { border: none;}");
    if (isLeft) {
        layout->addWidget(avatarBtn, 0, 0, 2, 1, Qt::AlignTop | Qt::AlignLeft);
    } else {
        layout->addWidget(avatarBtn, 0, 1, 2, 1, Qt::AlignTop | Qt::AlignLeft);
    }

    // 3. 创建名字和时间
    QLabel* nameLabel = new QLabel();
    nameLabel->setText(message.sender.name + " | " + message.time);
    nameLabel->setAlignment(Qt::AlignBottom);
    nameLabel->setStyleSheet("QLabel { font-size: 12px; color: rgb(178, 178, 178); }");
    if (isLeft) {
        layout->addWidget(nameLabel, 0, 1);
    } else {
        layout->addWidget(nameLabel, 0, 0, Qt::AlignRight);
    }

    // 4. 创建消息体
    QWidget* contentWidget = nullptr;
    switch (message.messageType) {
    case TEXT_TYPE:
        contentWidget = makeTextMessageItem(isLeft, message.content);
        break;
    case IMAGE_TYPE:
        contentWidget = makeImageMessageItem(isLeft, message);
        break;
    case FILE_TYPE:
        contentWidget = makeFileMessageItem(isLeft, message);
        break;
    case SOUND_TYPE:
        contentWidget = makeSoundMessageItem(isLeft, message);
        break;
    default:
        LOG() << "错误的消息类型! messageType=" << message.messageType;
    }
    if (isLeft)
    {
        layout->addWidget(contentWidget, 1, 1);
    } else
    {
        layout->addWidget(contentWidget, 1, 0);
    }
     connect(avatarBtn,&QPushButton::clicked,messageItem,[=](){
         MainWidget*mainWidget=MainWidget::getInstance();
         userInfoWidget*userinfoWidget=new  userInfoWidget(message.sender,mainWidget);
         userinfoWidget ->exec();
     });

     return  messageItem;
}

QWidget *MessageItem::makeTextMessageItem(bool isleft, const QString &text)
{

  MessageContentLabel* messageContentLabel = new MessageContentLabel(text, isleft, TEXT_TYPE, "", QByteArray());
    return messageContentLabel;
}

QWidget *MessageItem::makeFileMessageItem(bool isLeft, const Message&message)
{
    return nullptr;
}

QWidget *MessageItem::makeSoundMessageItem(bool isleft,const Message&message)
{
     return nullptr;
}

QWidget *MessageItem::makeImageMessageItem(bool isleft,const Message&message)
{
     return nullptr;
}

//////////////////////////////////
//创建具体文本消息
//////////////////////////////////
 MessageContentLabel::MessageContentLabel(const QString& text, bool isLeft, model::MessageType messageType, const QString& fileId,const QByteArray& content)
    :isleft(isLeft)
{
     QLabel* label=new QLabel(this);
     QFont font;
     font.setFamily("微软雅黑");
     font.setPixelSize(16);
     label->setText(text);
     label->setFont(font);

    label->setAlignment(Qt::AlignLeft|Qt::AlignHCenter);
    label->setWordWrap(true);
    label->setStyleSheet("QLabel{line-height:1.2;padding:0 10px;}");
}

   //要通过绘图时间去实现放文字外面的圆角矩形加图的实现
void MessageContentLabel::paintEvent(QPaintEvent *event)
{

    //想办法获取到文字的行数与列数，从而决定我们绘制矩形的尺寸
    //先获取到父元素的宽度
    QObject* object=this->parent();
    if (!object->isWidgetType())
    {
        LOG()<<"父元素类型错误";
        return;
    }

     QWidget* parent=dynamic_cast<QWidget*>(object);
        //我们允许字的宽度为总消息展示界面的0.6
        int width=(parent->width())*0.6;
    //去计算我们文字内容可以有多少行
    //1.总的宽度
    QFontMetrics Metrics(this->label->font());
    int totalWidth= Metrics.horizontalAdvance(this->label->text());
    //左右各有10边距
    int rows= totalWidth/(width-20)+1;
    if(rows==1)
    {
        width=totalWidth+20;
    }
    //计算总的高度
    int height=rows*(this->label->font().pixelSize()*1.2)+20;
    //根据上面算出的高度与宽度绘制圆角矩形与对应箭头
    QPainter painter(this);
    QPainterPath path;
    //设置抗锯齿
    painter.setRenderHint(QPainter::Antialiasing);
    if(isleft)
    {
        //pen是来画字体颜色的，brush是来画背景颜色的
        painter.setPen(QPen(QColor(255,255,255)));
        painter.setBrush(QColor(255,255,255));
       //先画一个圆角矩形
      painter.drawRoundedRect(10,0,width,height,10,10);
        path.moveTo(10,15);
        path.lineTo(0,20);
         path.lineTo(10,25);
         path.closeSubpath();
        this->label->setGeometry(10,0,width,height);
       painter.drawPath(path);

    }
    else
    {
        painter.setPen(QPen(QColor(137,217,97)));
        painter.setBrush(QColor(137,217,97));
        painter.drawRoundedRect(10,0,width,height,10,10);
        //10是用来容纳箭头的宽度
        int lefttop=this->width()-width-10;
        int righttop=this->width()-10;
       painter.drawRoundedRect(lefttop,0,width,height,10,10);
          //绘制箭头
        path.moveTo(righttop,15);
         path.lineTo(righttop+10,20);
        path.lineTo(righttop,25);
         path.closeSubpath();
       painter.drawPath(path);
    }
}
